import 'package:flutter/material.dart';
import 'package:flutter_demo/ui/pages/status/data/share_data_notifier.dart';

// 额外定义一个StatefulWidget类型的组件来包裹_InheritedWidget组件，使其可以具有状态更新功能
class ShareNotifierWidget extends StatefulWidget {
  final ShareDataNotifier shareData; // 共享数据
  final Widget child;

  ShareNotifierWidget({Key? key, required this.shareData, required this.child});

  @override
  State<ShareNotifierWidget> createState() => _ShareNotifierWidgetState();

  static ShareDataNotifier of(BuildContext context) {
    final _InheritedWidget? inheritedConfig =
        context.dependOnInheritedWidgetOfExactType<_InheritedWidget>();
    return inheritedConfig!.data;
  }
}

class _ShareNotifierWidgetState extends State<ShareNotifierWidget> {
  @override
  void initState() {
    super.initState();
    widget.shareData.addListener(notitierListener);
  }

  @override
  void dispose() {
    super.dispose();
    widget.shareData.removeListener(notitierListener);
  }

  void notitierListener() {
    //更新页面
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return _InheritedWidget(data: widget.shareData, child: widget.child);
  }
}

class _InheritedWidget extends InheritedWidget {
  _InheritedWidget({Key? key, required Widget child, required this.data})
      : super(key: key, child: child);

  final ShareDataNotifier data;

  @override
  bool updateShouldNotify(_InheritedWidget oldWidget) {
    //print(oldWidget.data.nickname);
    //print(data.nickname);
    //return oldWidget.data.nickname != data.nickname;

    return true;
  }
}
